//Erstellt von Moritz Liepe
package main.editor;

import java.io.File;

import main.XMLWriter;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;


public class SaveAsHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		String filename = "";
		boolean finished = false;
		while(!finished){
			FileDialog fileDialog = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE);
			fileDialog.setFilterPath("C:/");
			String[] extensions = { "*.xml", "*.*" };
			fileDialog.setFilterExtensions(extensions);
			filename = fileDialog.open();
			if((filename == null))return null;
			File file = new File(filename);
	        if (file.exists()) {
	          MessageBox ensure = new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.ICON_WARNING | SWT.YES | SWT.NO);
	          ensure.setMessage(filename + " already exists. Do you want to replace it?");
	          if (ensure.open() == SWT.YES) finished = true;
	          else {
	        	  finished = false;
	        	  continue;
	          }
	        }
	        else finished = true;
			XMLWriter writer = new XMLWriter(filename);
			writer.saveXMLDocument();
		}
		VOSEditor vosEditor;
		IEditorPart page = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getActiveEditor();
		if((page != null) && (page instanceof VOSEditor))
		{
			vosEditor = (VOSEditor)page;
			vosEditor.setFilename(filename);
			vosEditor.setDirty(false);
		}
		return null;
	}

}
